package com.chaoxin.lovehelp.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.chaoxin.lovehelp.service.RecipientService;
import com.chaoxin.lovehelp.common.enums.vo.allCategoryVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chaoxin.lovehelp.common.utils.PageUtils;

import com.chaoxin.lovehelp.dao.CategoryDao;
import com.chaoxin.lovehelp.entity.CategoryEntity;
import com.chaoxin.lovehelp.service.CategoryService;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Autowired
    RecipientService recipientService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        QueryWrapper<CategoryEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("is_display","1");
        List<CategoryEntity> categoryEntities = this.list(wrapper);
        List<allCategoryVo> vos = new ArrayList<>();

        //获取户数并赋值到allCategoryVo
        for (CategoryEntity category : categoryEntities) {
            allCategoryVo vo = new allCategoryVo();
            BeanUtils.copyProperties(category,vo);
            vo.setPersonsNum(recipientService.getPersonsNum(category.getId()));
            vos.add(vo);
        }
        //分页处理
        Integer pageIndex = Integer.parseInt(params.get("page").toString());
        Integer limit = Integer.parseInt(params.get("limit").toString());
        int from = (pageIndex - 1) * limit;
        int to = from + limit > vos.size() ? vos.size() : from + limit;
        List<allCategoryVo> vos1 = new ArrayList<>(vos.subList(from, to));
        IPage<allCategoryVo> page = new Page<>(pageIndex, limit);
        page.setRecords(vos1);
        page.setTotal(vos.size());
        page.setPages(vos.size() % limit > 0 ? vos.size() / limit + 1 : vos.size() / limit);
        return new PageUtils(page);
    }

    @Override
    public void removeIds(List<Integer> list) {
        if(list!=null){
            for (Integer id: list) {
                CategoryEntity category = this.baseMapper.selectById(id);
                category.setIsDisplay(0);
                this.baseMapper.updateById(category);
            }
        }
    }

    @Override
    public List<CategoryEntity> getAllCategory() {
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("is_display",1);

        List<CategoryEntity> list = this.list(wrapper);
        return list;
    }


}